﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
//using ASPPDFLib;
using System.Web;
using System.Net;
using System.Xml.Serialization;
using System.Data.SqlClient;
using System.Data.Odbc;
using System.Reflection;
using System.Net.Mail;
//using System.Web.Mail;
using System.Web.Caching;
//using ASPEMAILLib;
using System.Collections;
//using MiWebsSiteCore.Business;
using System.Globalization;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Data;
using System.Xml.Schema;




namespace WLMCoreLibrary
{
    public enum ErrorCode
    {
        //UserErrors
        none,
        UserNotLogged = 1,
        UserDontHaveAdd = 2,
        UserDontExist = 3,
        UserWrongPassword = 4


        ,
        PaymentError

            , CompilationError
    }

    public enum SuccessCode
    {
        none,
        RegistrySaved = 1,
        RegistryUpdated = 2,
        RegistryDeleted = 3,
        RegistryListGetted=4,

        UserLogged = 10,

        PaymentGenerated
    }

    [XmlType("Error")]
    public class ErrorObject
    {
        public string Description
        {
            get;
            set;

        }

        public ErrorCode Code
        {
            get;
            set;
        }

        public string ExeptionMessage
        {
            get;
            set;
        }

        public string StackTrace
        {
            get;
            set;
        }

        public ErrorObject()
        {

        }

        public ErrorObject(ErrorCode codigoError, string errorDescription, string exeption, string stack)
        {
            Code = codigoError;
            Description = errorDescription;
            ExeptionMessage = exeption;
            StackTrace = stack;
        }

        public ErrorObject(ErrorCode codigoError)
        {
            Code = codigoError;
        }

        public ErrorObject(ErrorCode codigoError, string errorDescription)
        {
            Code = codigoError;
            Description = errorDescription;

        }

    }

    [XmlType("Success")]
    public class SuccessObject
    {
        public SuccessCode Code
        {
            get;
            set;
        }

        public string Message
        {
            get;
            set;
        }

        public XmlNode Object
        {
            get;
            set;
        }

        public object Obj
        {
            get;
            set;
        }

        public bool success
        {
            get;
            set;
        }

        public SuccessObject()
        {
        }

        public SuccessObject(SuccessCode codigo)
        {
            Code = codigo;
        }

        public SuccessObject(SuccessCode codigo, string mensaje)
        {
            Code = codigo;
            Message = mensaje;
        }

        public SuccessObject(SuccessCode codigo, string mensaje, XmlNode obj)
        {
            Code = codigo;
            Message = mensaje;
            Object = obj;
        }
        public SuccessObject(SuccessCode codigo, string mensaje, object obj)
        {
            Code = codigo;
            Message = mensaje;
            Obj = obj;
        }
    }

    public class StringWriterWithEncoding : StringWriter
    {
        Encoding encoding;

        public StringWriterWithEncoding(Encoding encoding)
        {
            this.encoding = encoding;
        }

        public override Encoding Encoding
        {
            get { return encoding; }
        }
    }

    public struct PaginacionXML
    {
        private int _dataPage;

        public int DataPage
        {
            get { return _dataPage; }
            set { _dataPage = value; }
        }

        private int _rowsPerPage;

        public int RowsPerPage
        {
            get { return _rowsPerPage; }
            set { _rowsPerPage = value; }
        }

        private string _sortOrder;
        private string _limit;

        public string Limit
        {
            get { return _limit; }
            set { _limit = value; }
        }

        public string SortOrder
        {
            get { return _sortOrder; }
            set { _sortOrder = value; }
        }
    }

    public static class WLMFunctions
    {


        public static string AdminDataGrid(string consulta, string nuevoElementoScript, string ParametrosBusqueda, Boolean ponerBotonesAccion, int noRegistros, int pagina1, string panel, string nombrePagina, string panelSalida, string ActionScript, string NombreElementos, dbConnector ConexionDB)
        {
            if (panelSalida == "")
                panelSalida = "AjaxDiv";
            StringBuilder adminGrid = new StringBuilder();
            OdbcDataReader rsDatos;
            int pagina, paginaActual, numeroPaginas = 0, totalRegistros;
            //    dim rsDatos,x,y,z,numeroPaginas,tabla,paginaActual,salida,f1,f2,filtroF

            int tamanoPagina = Convert.ToInt32(ConfigurationManager.AppSettings["tamanoPagina"]);
            if (noRegistros != 0)
                tamanoPagina = noRegistros;
            if (nombrePagina.Contains("?"))
                nombrePagina += "&";
            else
                nombrePagina += "?";

            //if (ActionScript.Contains("?"))
            //    urlSalida += "&";
            //else
            //    urlSalida += "?";





            if (HttpContext.Current.Request.QueryString["sort"] != null)
            {
                consulta += " ORDER BY " + HttpContext.Current.Request.QueryString["sort"].ToString();
                if (HttpContext.Current.Request.QueryString["desc"] == "1")
                    consulta += " DESC";
            }
            else
                consulta += " ORDER BY id DESC";

            pagina = Convert.ToInt32(HttpContext.Current.Request.QueryString["pagina"]);
            //HttpContext.Current.Response.Write(pagina + "cosas");
            if (pagina == 0)
                pagina = 1;

            paginaActual = pagina;
            pagina = (pagina - 1) * tamanoPagina;

            rsDatos = ConexionDB.ExecuteReader(consulta);
            if (rsDatos.HasRows)
            {
                //totalRegistros = ConexionDB.ExecuteRecordCount(consulta);
                //numeroPaginas = totalRegistros / tamanoPagina;
            }
            consulta += " LIMIT " + pagina + "," + tamanoPagina;
            rsDatos = ConexionDB.ExecuteReader(consulta);

            if (HttpContext.Current.Request.QueryString["ajax"] == "1")
                adminGrid.Append("<div id='" + panel + "' style='position:relative;top:0;left:0;width:auto;height:auto'> ");

            string sorting = "0";
            int x;
            //adminGrid.Append("<div>");

            if (ponerBotonesAccion)
            {
                if (nuevoElementoScript == "")
                    adminGrid.Append("<div id='botonelementos'><input type='button' onClick=\"$('#" + panelSalida + "').load('" + nombrePagina + "addElement=1&ajax=1&panel=" + panelSalida + "');\" value='Nuevo " + NombreElementos + "'/><input type=textbox id='Buscador" + panelSalida + "' value='" + HttpContext.Current.Request.QueryString["buscar"] + "'><input type=button value='Buscar  " + NombreElementos + "' onClick=\"var PaginaBusqueda='" + nombrePagina + "desc=" + sorting + "&pagina=" + ((pagina / tamanoPagina) + 1).ToString() + "&ajax=1&panel=" + panelSalida + "&buscar='+$('#Buscador" + panelSalida + "').val()+''; $('#" + panelSalida + "').load(PaginaBusqueda);\"></div>");

                else
                    adminGrid.Append("<div id='botonelementos'><input type='button' onClick=\"" + nuevoElementoScript + "\" value='Nuevo " + NombreElementos + "'/><input type=textbox id='Buscador" + panelSalida + "' value='" + HttpContext.Current.Request.QueryString["buscar"] + "'><input type=button value='Buscar  " + NombreElementos + "' onClick=\"var PaginaBusqueda='" + nombrePagina + "desc=" + sorting + "&pagina=" + ((pagina / tamanoPagina) + 1).ToString() + "&ajax=1&panel=" + panelSalida + "&buscar='+$('#Buscador" + panelSalida + "').val()+''; $('#" + panelSalida + "').load(PaginaBusqueda);\"></div>");

            }

            adminGrid.Append("<span><table width='100%' border='0' cellspacing='0' cellpadding='0' id='tablaAdmin'><tr>"); //<th width='20px'><input type='checkbox' id='' class='checkBoxPanel'></th>

            for (x = 0; x < rsDatos.FieldCount; x++)
            {

                if (HttpContext.Current.Request.QueryString["sort"] == rsDatos.GetName(x) && HttpContext.Current.Request.QueryString["desc"] == "0")
                    sorting = "1";
                else
                    sorting = "0";
                adminGrid.Append("<th style=\"cursor:hand;\" onClick=\"$('#" + panelSalida + "').load('" + nombrePagina + "sort=" + rsDatos.GetName(x) + "&desc=" + sorting + "&pagina=" + ((pagina / tamanoPagina) + 1).ToString() + "&ajax=1&panel=" + panelSalida + "&buscar=" + HttpContext.Current.Request.QueryString["buscar"] + "');\" nowrap>" + rsDatos.GetName(x));
                if (HttpContext.Current.Request.QueryString["sort"] != null)
                    if (HttpContext.Current.Request.QueryString["sort"].ToString() == rsDatos.GetName(x))
                        if (sorting == "1")
                            adminGrid.Append(" <img src='/img/sorteddesc.gif'>");
                        else
                            adminGrid.Append(" <img src='/img/sortedasc.gif'>");
                adminGrid.Append("</th>");

            }

            string[] parametros = ParametrosBusqueda.Split(',');
            StringBuilder cadenaBusqueda = new StringBuilder();
            int cantidadCadenas = parametros.Length;
            if (ParametrosBusqueda != "")
                if (HttpContext.Current.Request.QueryString["buscar"] != null)
                {
                    string parametroBusqueda = "";
                    parametroBusqueda = HttpContext.Current.Request.QueryString["buscar"];
                    if (consulta.Contains("WHERE"))
                    {
                        string[] separador = { "WHERE" };
                        string[] cons = consulta.Split(separador, StringSplitOptions.None);
                        cadenaBusqueda.Append(" AND (");
                        foreach (string cad in parametros)
                        {
                            if (cad != "id")
                                cadenaBusqueda.Append(cad + " LIKE '%" + parametroBusqueda + "%' ");
                            cantidadCadenas--;
                            if (cantidadCadenas >= 1)
                                if (cad != "id")
                                    cadenaBusqueda.Append(" OR ");
                        }
                        cadenaBusqueda.Append(")");
                    }
                    else
                    {
                        cadenaBusqueda.Append(" WHERE ");
                        foreach (string cad in parametros)
                        {
                            if (cad != "id")
                                cadenaBusqueda.Append(cad + " LIKE '%" + parametroBusqueda + "%' ");
                            cantidadCadenas--;
                            if (cantidadCadenas >= 1)
                                if (cad != "id")
                                    cadenaBusqueda.Append(" OR ");
                        }
                    }
                }

            string consultaConteo = "";
            if (consulta.Contains("ORDER"))
            {
                string[] separador1 = { "ORDER" };
                string[] consul = consulta.Split(separador1, StringSplitOptions.None);
                consulta = consul[0] + cadenaBusqueda.ToString() + " ORDER " + consul[1];
                consultaConteo = consul[0] + cadenaBusqueda.ToString();
            }
            else
            {
                if (consulta.Contains("LIMIT"))
                {
                    string[] separador1 = { "LIMIT" };
                    string[] consul = consulta.Split(separador1, StringSplitOptions.None);
                    consulta = consul[0] + cadenaBusqueda.ToString() + " LIMIT " + consul[1];
                    consultaConteo = consul[0] + cadenaBusqueda.ToString();
                }
                else
                {
                    consulta = consulta + cadenaBusqueda.ToString();
                    consultaConteo = consulta;
                }
            }
            totalRegistros = ConexionDB.ExecuteRecordCount(consultaConteo);
            numeroPaginas = totalRegistros / tamanoPagina;
            //HttpContext.Current.Response.Write(consulta);
            //HttpContext.Current.Response.End();
            rsDatos = ConexionDB.ExecuteReader(consulta);
            adminGrid.Append("<th >&nbsp;</th></tr>");
            while (rsDatos.Read())
            {
                //adminGrid.Append("<td width='20px'><input type='checkbox' id='" + Convert.ToString(rsDatos["id"]) + "' class='checkBoxPanel'></td>");
                if (ActionScript == "")
                    adminGrid.Append("<tr style='cursor:hand;' onClick=\"$('#" + panelSalida + "').load('" + nombrePagina + "desc=1&id=" + rsDatos[0] + "&ajax=1&panel=" + panelSalida + "');\" >");
                else
                {
                    string action = ActionScript.ToString();
                    action = action.Replace("ID", rsDatos[0].ToString());
                    adminGrid.Append("<tr style='cursor:hand;' onClick=\"" + action + "\" >");
                }
                for (x = 0; x < rsDatos.FieldCount; x++)
                {
                    switch (rsDatos.GetFieldType(x).ToString())
                    {
                        //case "System.Int32":
                        //    field.SetValue(classObject, (System.Int32)reader[x]);
                        //    break;
                        //case "System.DateTime":
                        //    field.SetValue(classObject, Convert.ToDateTime(reader[x]));
                        //    break;
                        case "System.Decimal":
                            if (!rsDatos.IsDBNull(x))
                                adminGrid.Append("<td onMouseOver=\"this.className='TRAlt';\" onMouseOut=\"this.className='';\" nowrap>" + Convert.ToDecimal(rsDatos[x]).ToString("C") + "&nbsp;</td>");
                            else
                                adminGrid.Append("<td onMouseOver=\"this.className='TRAlt';\" onMouseOut=\"this.className='';\" nowrap>&nbsp;</td>");

                            break;
                        //case "System.String":
                        //    field.SetValue(classObject, (System.String)reader[x]);
                        //    break;
                        //case "System.Int16":
                        //    field.SetValue(classObject, Convert.ToBoolean(reader[x]));
                        //    break;
                        //case "System.Boolean":
                        //field.SetValue(classObject, Convert.ToBoolean(reader[field.Name.ToString().Substring(1)].ToString()));
                        //break;
                        default:
                            if (!rsDatos.IsDBNull(x))
                                adminGrid.Append("<td onMouseOver=\"this.className='TRAlt';\" onMouseOut=\"this.className='';\" nowrap>" + Convert.ToString(rsDatos[x]) + "&nbsp;</td>");
                            else
                                adminGrid.Append("<td onMouseOver=\"this.className='TRAlt';\" onMouseOut=\"this.className='';\" nowrap>&nbsp;</td>");
                            break;
                    }
                }

                if (ActionScript == "")
                    adminGrid.Append("<td width='20'><a href='javascript:void(0);' onClick=\"$('#" + panelSalida + "').load('" + nombrePagina + "desc=1&id=" + rsDatos[0] + "&ajax=1&panel=" + panelSalida + "');\" ><img src='/img/vistaPrevia.png' width='17' border='0'></a></td>");
                else
                {
                    string action = ActionScript.ToString();
                    action = action.Replace("ID", rsDatos[0].ToString());
                    adminGrid.Append("<td width='20'><a href='javascript:void(0);' onClick=\"" + action + "\" ><img src='/img/vistaPrevia.png' width='17' border='0'></a></td>");
                }

                //adminGrid.Append("<td width='20'><a href='javascript:void(0);' onClick=\"\" ><img src='/img/editar.png' width='20' border='0'></a></td>");
                //adminGrid.Append("<td width='20'><a href='javascript:void(0);' onClick=\"\" ><img src='/img/cancelar2.png' width='20' border='0'></a></td>");

                adminGrid.Append("</tr><tr>");

            }
            adminGrid.Append("</tr><tr><td colspan='" + rsDatos.FieldCount + 1 + "'>");
            for (x = 1; x <= numeroPaginas + 1; x++)
            {
                string desc;
                if (HttpContext.Current.Request.QueryString["desc"] == "1")
                    desc = "1";
                else
                    desc = "0";
                adminGrid.Append("<span style=\"cursor:hand;font-size:8px;\" onClick=\"$('#" + panelSalida + "').load('" + nombrePagina + "desc=" + desc + "&pagina=" + x + "&ajax=1&panel=" + panelSalida + "&buscar=" + HttpContext.Current.Request.QueryString["buscar"]);
                if (HttpContext.Current.Request.QueryString["sort"] != null)
                    adminGrid.Append("&sort=" + HttpContext.Current.Request.QueryString["sort"]);
                else
                    adminGrid.Append("&sort=id");

                adminGrid.Append("');\"");

                if (paginaActual == x)
                    adminGrid.Append("'><b>[ " + x + " ]</b></span> ");
                else
                    adminGrid.Append("'>[ " + x + " ]</span> ");
            }
            adminGrid.Append("</td></tr></table></span>");
            if (HttpContext.Current.Request.QueryString["ajax"] == "1")
                adminGrid.Append("</div> ");

            return adminGrid.ToString();
        }

        //public static string NubeTags(ref dbConnector ConexionDB)
        //{
        //    StringBuilder nube = new StringBuilder();
        //    if (Convert.ToString(HttpContext.Current.Application["NubeTags"]) == "")
        //    {
        //        //HttpContext.Current.Response.Write("nube de tags generada");
        //        MiWebSiteBlogTagCollection listaTags = new MiWebSiteBlogTagCollection(ConexionDB);


        //        int maximo = 0;
        //        foreach (MiWebSiteBlogTag tag in listaTags.Elementos)
        //        {
        //            string strCommand = "select sum(1) as total from blogentry WHERE tags like '%" + tag.NombreTag + "%'";
        //            OdbcDataReader rsDatos2 = ConexionDB.ExecuteReader(strCommand);
        //            if (rsDatos2.Read())
        //            {
        //                if (!rsDatos2.IsDBNull(0))
        //                {
        //                    int temporal = Convert.ToInt32(rsDatos2["total"]);
        //                    if (temporal > maximo)
        //                        maximo = temporal;
        //                }
        //            }

        //        }

        //        foreach (MiWebSiteBlogTag tag in listaTags.Elementos)
        //        {
        //            string strCommand = "select sum(1) as total from blogentry WHERE tags like '%" + tag.NombreTag + "%'";
        //            OdbcDataReader rsDatos2 = ConexionDB.ExecuteReader(strCommand);
        //            rsDatos2.Read();
        //            string temporal = " <span><a href='/blog/tag/" + tag.NombreTag + ".aspx' style=\"font-size:";
        //            int totalTags = 0;
        //            if (!rsDatos2.IsDBNull(0))
        //            {
        //                totalTags = Convert.ToInt32(rsDatos2["total"]);
        //            }
        //            int pix = (totalTags * 28) / maximo;
        //            if (pix > 9)
        //                temporal += pix.ToString();
        //            else
        //                temporal += "9";
        //            temporal += "px\">" + tag.NombreTag + "</a></span>";
        //            nube.Append(temporal);
        //        }
        //        HttpContext.Current.Application.Add("NubeTags", "<div>" + nube.ToString() + "</div>");
        //    }
        //    return HttpContext.Current.Application["NubeTags"].ToString();
        //}

        public static string NumeroALetras(string num, string Unidad)
        {

            string res, dec = "";

            Int64 entero;

            int decimales;

            double nro;

            try
            {

                nro = Convert.ToDouble(num);

            }

            catch
            {

                return "";

            }

            entero = Convert.ToInt64(Math.Truncate(nro));

            decimales = Convert.ToInt32(Math.Round((nro - entero) * 100, 2));

            if (decimales >= 0)
            {

                if (decimales < 10)
                {
                    dec = " 0" + decimales.ToString() + "/100";
                }
                else
                {
                    dec = " " + decimales.ToString() + "/100";
                }

            }


            res = toText(Convert.ToDouble(entero)) + " " + Unidad + dec;

            return res;

        }

        private static string toText(double value)
        {

            string Num2Text = "";

            value = Math.Truncate(value);

            if (value == 0) Num2Text = "CERO";

            else if (value == 1) Num2Text = "UNO";

            else if (value == 2) Num2Text = "DOS";

            else if (value == 3) Num2Text = "TRES";

            else if (value == 4) Num2Text = "CUATRO";

            else if (value == 5) Num2Text = "CINCO";

            else if (value == 6) Num2Text = "SEIS";

            else if (value == 7) Num2Text = "SIETE";

            else if (value == 8) Num2Text = "OCHO";

            else if (value == 9) Num2Text = "NUEVE";

            else if (value == 10) Num2Text = "DIEZ";

            else if (value == 11) Num2Text = "ONCE";

            else if (value == 12) Num2Text = "DOCE";

            else if (value == 13) Num2Text = "TRECE";

            else if (value == 14) Num2Text = "CATORCE";

            else if (value == 15) Num2Text = "QUINCE";

            else if (value < 20) Num2Text = "DIECI" + toText(value - 10);

            else if (value == 20) Num2Text = "VEINTE";

            else if (value < 30) Num2Text = "VEINTI" + toText(value - 20);

            else if (value == 30) Num2Text = "TREINTA";

            else if (value == 40) Num2Text = "CUARENTA";

            else if (value == 50) Num2Text = "CINCUENTA";

            else if (value == 60) Num2Text = "SESENTA";

            else if (value == 70) Num2Text = "SETENTA";

            else if (value == 80) Num2Text = "OCHENTA";

            else if (value == 90) Num2Text = "NOVENTA";

            else if (value < 100) Num2Text = toText(Math.Truncate(value / 10) * 10) + " Y " + toText(value % 10);

            else if (value == 100) Num2Text = "CIEN";

            else if (value < 200) Num2Text = "CIENTO " + toText(value - 100);

            else if ((value == 200) || (value == 300) || (value == 400) || (value == 600) || (value == 800)) Num2Text = toText(Math.Truncate(value / 100)) + "CIENTOS";

            else if (value == 500) Num2Text = "QUINIENTOS";

            else if (value == 700) Num2Text = "SETECIENTOS";

            else if (value == 900) Num2Text = "NOVECIENTOS";

            else if (value < 1000) Num2Text = toText(Math.Truncate(value / 100) * 100) + " " + toText(value % 100);

            else if (value == 1000) Num2Text = "MIL";

            else if (value < 2000) Num2Text = "MIL " + toText(value % 1000);

            else if (value < 1000000)
            {

                Num2Text = toText(Math.Truncate(value / 1000)) + " MIL";

                if ((value % 1000) > 0) Num2Text = Num2Text + " " + toText(value % 1000);

            }

            else if (value == 1000000) Num2Text = "UN MILLON";

            else if (value < 2000000) Num2Text = "UN MILLON " + toText(value % 1000000);

            else if (value < 1000000000000)
            {

                Num2Text = toText(Math.Truncate(value / 1000000)) + " MILLONES ";

                if ((value - Math.Truncate(value / 1000000) * 1000000) > 0) Num2Text = Num2Text + " " + toText(value - Math.Truncate(value / 1000000) * 1000000);

            }

            else if (value == 1000000000000) Num2Text = "UN BILLON";

            else if (value < 2000000000000) Num2Text = "UN BILLON " + toText(value - Math.Truncate(value / 1000000000000) * 1000000000000);

            else
            {

                Num2Text = toText(Math.Truncate(value / 1000000000000)) + " BILLONES";

                if ((value - Math.Truncate(value / 1000000000000) * 1000000000000) > 0) Num2Text = Num2Text + " " + toText(value - Math.Truncate(value / 1000000000000) * 1000000000000);

            }

            return Num2Text;

        }

        public static decimal MonedaADecimal(string moneda)
        {
            if (moneda != null)
            {
                moneda = moneda.Replace("$", "");
                moneda = moneda.Replace("%", "");
                moneda = moneda.Replace(",", "");
                try
                {
                    return Convert.ToDecimal(moneda);
                }
                catch (Exception ex)
                {
                    ErrorManagement.LogError(ex, HttpContext.Current, null, null);
                    return 0;
                }
            }
            else
                return 0;
        }

        public static string limitePaginas(int numeroPagina)
        {
            return ((numeroPagina - 1) * Convert.ToInt32(ConfigurationManager.AppSettings["tamanoPagina"])).ToString() + "," + ConfigurationManager.AppSettings["tamanoPagina"];
        }

        #region XML Serialization

        /// <summary>
        /// To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
        /// </summary>
        /// <param name="characters">Unicode Byte Array to be converted to String</param>
        /// <returns>String converted from Unicode Byte Array</returns>
        private static String UTF8ByteArrayToString(Byte[] characters)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            String constructedString = encoding.GetString(characters);
            return (constructedString);
        }


        /// <summary>
        /// Converts the String to UTF8 Byte array and is used in De serialization
        /// </summary>
        /// <param name="pXmlString"></param>
        /// <returns></returns>
        private static Byte[] StringToUTF8ByteArray(String pXmlString)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(pXmlString);
            return byteArray;
        }

        public static XmlDocument SerializeObject(Object pObject)
        {
            ////try
            ////{
            //    XmlDocument xmlDocument = new XmlDocument();
            //    String xmlSerializedString = null;
            //    MemoryStream memoryStream = new MemoryStream();
            //    XmlSerializer xs = new XmlSerializer(pObject.GetType());
            //    XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

            //    xs.Serialize(xmlTextWriter, pObject);
            //    memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
            //    xmlSerializedString = UTF8ByteArrayToString(memoryStream.ToArray());
            //    //xmlSerializedString = xmlSerializedString.Replace("\"", "'");
            //    //xmlSerializedString = xmlSerializedString.Trim();
            //    xmlDocument.Load(xmlTextWriter.BaseStream);
            //    return xmlDocument;
            //    //return xmlSerializedString;
            ////}
            ////catch (Exception e)
            ////{
            ////    System.Console.WriteLine(e);
            ////    HttpContext.Current.Response.Write(e.Message);
            ////    HttpContext.Current.Response.End();
            ////    return null;
            ////}
            XmlSerializer ser = new XmlSerializer(pObject.GetType());
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            System.IO.StringWriter writer = new StringWriterWithEncoding(Encoding.UTF8);
            ser.Serialize(writer, pObject);
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(writer.ToString());
            return doc;
        }

        public static string SerializeObject(Object pObject, bool cosas)
        {
            //try
            //{
            XmlDocument xmlDocument = new XmlDocument();
            String xmlSerializedString = null;
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.IndentChars = "\t";
            settings.Encoding = Encoding.UTF8;
            MemoryStream memoryStream = new MemoryStream();
            XmlSerializer xs = new XmlSerializer(pObject.GetType());
            XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

            xs.Serialize(xmlTextWriter, pObject);
            memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
            xmlSerializedString = UTF8ByteArrayToString(memoryStream.ToArray());
            //xmlSerializedString = xmlSerializedString.Replace("\"", "'");
            //xmlSerializedString = xmlSerializedString.Trim();
            //xmlDocument.LoadXml(xmlSerializedString);
            //return xmlDocument;
            return xmlSerializedString;
            //}
            //catch (Exception e)
            //{
            //    System.Console.WriteLine(e);
            //    HttpContext.Current.Response.Write(e.Message);
            //    HttpContext.Current.Response.End();
            //    return null;
            //}
        }

        #endregion

        public static string comillas(string cadenaOriginal)
        {
            if (cadenaOriginal != null)
                return cadenaOriginal.Replace("\"", "\\\"").Replace("\'", "\\\'");
            else
                return "";
            //cadenaOriginal = cadenaOriginal.Replace('"', '\"');

        }

        public static string CleanQuery(string sqlQuery)
        {
            string[] listaBanned = new string[] { "select", "drop", ";", "--", "insert", "delete", "xp_", "update", "into", "left join", "union" };
            foreach (string keyWord in listaBanned)
            {
                sqlQuery = sqlQuery.Replace(keyWord, "");
            }
            return sqlQuery;
        }

        public static string comillas(decimal cadenaOriginal)
        {
            if (cadenaOriginal != null)
                return cadenaOriginal.ToString().Replace("\"", "\\\"");
            else
                return "";
            //cadenaOriginal = cadenaOriginal.Replace('"', '\"');

        }

        public static string comillas(int cadenaOriginal)
        {
            if (cadenaOriginal != null)
                return cadenaOriginal.ToString().Replace("\"", "\\\"");
            else
                return "";
            //cadenaOriginal = cadenaOriginal.Replace('"', '\"');

        }

        public static string permanentLink(string postName, string seccion, DateTime fecha)
        {
            return "/" + seccion + "/" + fecha.Year + "/" + fecha.Month + "/" + fecha.Day + "/" + postName + "/";
        }

        public static string AutocompletarText(string idTextBox, string opciones)
        {
            StringBuilder salida = new StringBuilder();
            salida.Append("<script language=javascript>");
            salida.Append("$().ready(function() {");
            salida.Append("$(\"#" + idTextBox + "\").autocomplete([" + opciones + "], {");
            salida.Append("width: 320, max: 4,highlight: false,multiple: true,    multipleSeparator: \", \", scroll: true,  scrollHeight: 300}); }); </script>");
            return salida.ToString();
        }

        public static System.Boolean IsNumeric(System.Object Expression)
        {
            if (Expression == null || Expression is DateTime)
                return false;

            if (Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
                return true;

            try
            {
                if (Expression is string)
                    Double.Parse(Expression as string);
                else
                    Double.Parse(Expression.ToString());
                return true;
            }
            catch { } // just dismiss errors but return false
            return false;
        }

        public static bool TryParseToInt(string expression, out int iIntVal)
        {
            double dVal;
            bool bRes;

            bRes = double.TryParse(expression,
            NumberStyles.Integer,
            NumberFormatInfo.CurrentInfo,
            out dVal);

            if (dVal > Int32.MaxValue || dVal < Int32.MinValue)
            {
                iIntVal = 0;
                bRes = false;
            }
            else
                iIntVal = Convert.ToInt32(dVal);

            return bRes;
        }

        public static string Encrypt(string stringToEncrypt)
        {
            MD5CryptoServiceProvider MDHasher = new MD5CryptoServiceProvider();
            UTF8Encoding encoder = new UTF8Encoding();
            Byte[] hashedDataBytes = MDHasher.ComputeHash(encoder.GetBytes(stringToEncrypt));
            StringBuilder salida = new StringBuilder();
            foreach (Byte b in hashedDataBytes)
            {
                salida.Append(b.ToString());
            }

            return salida.ToString();
        }

        public static string EncodePassword(string originalPassword)
        {
            //Declarations
            Byte[] originalBytes;
            Byte[] encodedBytes;
            MD5 md5;

            //Instantiate MD5CryptoServiceProvider, get bytes for original password and compute hash (encoded password)
            md5 = new MD5CryptoServiceProvider();
            originalBytes = ASCIIEncoding.Default.GetBytes(originalPassword);
            encodedBytes = md5.ComputeHash(originalBytes);

            //Convert encoded bytes back to a 'readable' string
            return BitConverter.ToString(encodedBytes);
        }

        public static bool IsValidEmailAddress(string sEmail)
        {
            if (sEmail == null)
            {
                return false;
            }
            else
            {
                string patternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
                        + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                        + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                        + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                        + @"[a-zA-Z]{2,}))$";
                return Regex.IsMatch(sEmail, patternStrict, RegexOptions.IgnorePatternWhitespace); /*@"
^
[-a-zA-Z0-9][-.a-zA-Z0-9]*
@
[-.a-zA-Z0-9]+
(\.[-.a-zA-Z0-9]+)*
\.
(
com|edu|info|gov|int|mil|net|org|biz|
name|museum|coop|aero|pro|me|mx
|
[a-zA-Z]{2}
)
$",
                RegexOptions.IgnorePatternWhitespace);*/
            }
        }

        public static string CreateRandomPassword(int PasswordLength)
        {
            string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@";
            Random rNum = new Random();
            string NewPassWord = "";
            for (int i = 0; i < PasswordLength; i++)
            {
                NewPassWord += allowedChars[rNum.Next(allowedChars.Length)];
            }
            return NewPassWord;
        }

        public static string CreateRandomPasswordNumeric(int PasswordLength)
        {
            string allowedChars = "0123456789";
            Random rNum = new Random();
            string NewPassWord = "";
            for (int i = 0; i < PasswordLength; i++)
            {
                NewPassWord += allowedChars[rNum.Next(allowedChars.Length)];
            }
            return NewPassWord;
        }

        public static string GetMD5(string str)
        {
            MD5 md5 = MD5CryptoServiceProvider.Create();
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] stream = null;
            StringBuilder sb = new StringBuilder();
            stream = md5.ComputeHash(encoding.GetBytes(str));
            for (int i = 0; i < stream.Length; i++) sb.AppendFormat("{0:x2}", stream[i]);
            return sb.ToString();
        }

        public static string TransformXML(string strXMLURL, string strXSLURL, List<ParametroTransformacionXML> parametros)
        {
            //Create a IO Stream
            System.IO.StringWriter oSW = new System.IO.StringWriter();
            //try
            //{
            XmlTextReader oXR = new XmlTextReader(strXMLURL);

            XmlUrlResolver resolver = new XmlUrlResolver();
            resolver.Credentials = System.Net.CredentialCache.DefaultCredentials;



            XPathDocument oXPath = new XPathDocument(oXR);

            XslCompiledTransform transform = new XslCompiledTransform();

            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ProhibitDtd = false;
            settings.IgnoreComments = true;
            settings.ConformanceLevel = ConformanceLevel.Document;

            //settings.
            settings.ValidationType = ValidationType.DTD;
            settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);


            // Create the XmlReader object.

            XmlReader reader = XmlReader.Create(strXSLURL, settings);


            transform.Load(reader, XsltSettings.TrustedXslt, new XmlUrlResolver());
            //oXSLT.Transform(oXPath,argumentos, oSW);
            XmlWriterSettings settings2 = new XmlWriterSettings();
            settings2.Indent = true;
            settings2.Encoding = Encoding.UTF8;
            settings2.ConformanceLevel = ConformanceLevel.Fragment;
            settings2.OmitXmlDeclaration = true;


            System.Xml.Xsl.XsltArgumentList argumentos = new System.Xml.Xsl.XsltArgumentList();
            if (parametros != null)
                foreach (ParametroTransformacionXML par in parametros)
                    if (par.NombreParametro != null && par.Parametro != null)
                        argumentos.AddParam(par.NombreParametro, "", par.Parametro);
            if (HttpContext.Current != null)
                if (CurrentUser.IdUsuario != 0)
                {
                    argumentos.AddParam("administracion", "", "true");
                    argumentos.AddParam("username", "", CurrentUser.UserName);
                    argumentos.AddParam("userID", "", CurrentUser.IdUsuario);
                    argumentos.AddParam("userProfile", "", CurrentUser.NivelUsuario.ToString());
                }
            //argumentos.AddParam("domainname", "", CurrentDomain.DomainName);
            //argumentos.AddParam("subdomainname", "", CurrentDomain.SubDomain);
            //argumentos.AddParam("domainCity", "", CurrentDomain.Ciudad);

            //oXSLT.Transform(oXPath, argumentos, oSW,resolver);


            transform.Transform(oXPath, argumentos, XmlWriter.Create(oSW, settings2), resolver);


            //}
            //catch (System.Exception e)
            //{
            //    Put in custom error handler here...
            //    string x = e.ToString();
            //}
            //string message = oSW.ToString();
            //UTF8Encoding utf8 = new UTF8Encoding();

            //Byte[] encodedBytes = utf8.GetBytes(message);

            //message = encodedBytes.ToString();
            //return message;
            reader.Close();
            return oSW.ToString();
        }

        //public static string TransformXML(XmlDocument xd, string xslFileName, List<ParametroTransformacionXML> parametros)
        //{
        //    var xslt = new System.Xml.Xsl.XslCompiledTransform();
        //    xslt.Load(xslFileName);
        //    var stm = new MemoryStream();
        //    xslt.Transform(xd, null, stm);
        //    stm.Position = 1;
        //    var sr = new StreamReader(stm);
        //    //xtr.Close();
        //    return sr.ReadToEnd();
        //}
        public static string TransformXML(string strXMLURL, string strXSLURL)
        {
            return TransformXML(strXMLURL, strXSLURL, null);

        }

        public static string TransformXML(object data, string xslFileName)
        {

            return TransformXML(data, xslFileName, null);
        }

        public static string TransformXML(object data, string xslFileName, List<ParametroTransformacionXML> parametros)
        {

            System.IO.StringWriter oSW = new System.IO.StringWriter();
            XmlSerializer xs = new XmlSerializer(data.GetType());
            string xmlString;
            using (StringWriter swr = new StringWriterWithEncoding(Encoding.UTF8))// new StringWriter())
            {

                xs.Serialize(swr, data);
                xmlString = swr.ToString();
            }

            StringReader strReader = new StringReader(xmlString);
            XPathDocument oXPath = new XPathDocument(strReader);

            XslCompiledTransform transform = new XslCompiledTransform();
            XmlUrlResolver resolver = new XmlUrlResolver();
            resolver.Credentials = System.Net.CredentialCache.DefaultCredentials;
            var xslt = new System.Xml.Xsl.XslCompiledTransform();
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ProhibitDtd = false;
            settings.IgnoreComments = true;
            settings.ConformanceLevel = ConformanceLevel.Document;

            //settings.
            settings.ValidationType = ValidationType.DTD;
            settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

            XmlReader reader = XmlReader.Create(xslFileName, settings);

            transform.Load(reader, XsltSettings.TrustedXslt, new XmlUrlResolver());

            //oXSLT.Transform(oXPath,argumentos, oSW);
            XmlWriterSettings settings2 = new XmlWriterSettings();
            settings2.Indent = true;
            settings2.Encoding = Encoding.UTF8;
            settings2.ConformanceLevel = ConformanceLevel.Fragment;
            settings2.OmitXmlDeclaration = true;


            System.Xml.Xsl.XsltArgumentList argumentos = new System.Xml.Xsl.XsltArgumentList();
            if (parametros != null)
                foreach (ParametroTransformacionXML par in parametros)
                    if (par.NombreParametro != null && par.Parametro != null)
                        argumentos.AddParam(par.NombreParametro, "", par.Parametro);
            if (HttpContext.Current != null)
                if (CurrentUser.IdUsuario != 0)
                {
                    argumentos.AddParam("administracion", "", "true");
                    argumentos.AddParam("username", "", CurrentUser.UserName);
                    argumentos.AddParam("userID", "", CurrentUser.IdUsuario);
                    argumentos.AddParam("userProfile", "", CurrentUser.NivelUsuario.ToString());
                }


            transform.Transform(oXPath, argumentos, XmlWriter.Create(oSW, settings2), resolver);
            reader.Close();
            return oSW.ToString();
        }

        public static void ValidationCallBack(object sender, ValidationEventArgs e)
        {
            Console.WriteLine("Validation Error: {0}", e.Message);
        }

        public static void JsonGrid(string strCommand, string FieldList, string where, int dataPage)
        {
            JsonGrid(strCommand, FieldList, where, dataPage, true);
        }

        public static string JsonGrid(string strCommand, string FieldList, string where, int dataPage, bool endResponse)
        {
            dbConnector conexion = new dbConnector();
            OdbcDataAdapter adapter = new OdbcDataAdapter(strCommand, conexion.connector);
            DataTable dataTable = new DataTable();
            try
            {
                adapter.Fill(dataTable);
                OdbcDataAdapter adaptorCounter = new OdbcDataAdapter(FieldList + where, conexion.connector);
                DataTable counterTable = new DataTable();
                int registrosTotales = adaptorCounter.Fill(counterTable);

                HttpContext.Current.Response.AddHeader("Expires", " Mon, 26 Jul 1997 05:00:00 GMT");
                HttpContext.Current.Response.AddHeader("Last-Modified", DateTime.UtcNow.ToString());
                HttpContext.Current.Response.AddHeader("Cache-Control", " no-cache, must-revalidate");
                HttpContext.Current.Response.AddHeader("Pragma", "no-cache");
                HttpContext.Current.Response.AddHeader("Content-type", "text");


                StringBuilder salida = new StringBuilder();
                int totalRegistros = registrosTotales;
                salida.Append("{\n");
                salida.Append("\"page\": " + dataPage + ",\n");
                salida.Append("\"total\": " + totalRegistros + ",\n");
                salida.Append("\"rows\": [");
                bool initialRecord = false;
                foreach (DataRow dataRow in dataTable.Rows)
                {
                    if (initialRecord) salida.Append(",");
                    salida.Append("\n{");
                    salida.Append("\"id\":\"" + dataRow["id"] + "\",");

                    if (dataRow.Table.Columns.Contains("rowStatus"))
                    {
                        salida.Append("\"rowStatus\":\"" + dataRow["rowStatus"] + "\",");
                    }
                    salida.Append("\"cell\":[");
                    bool initialRecordCell = false;
                    foreach (object item in dataRow.ItemArray)
                    {
                        if (initialRecordCell) salida.Append(",");
                        salida.Append("\"" + item.ToString().Replace("\"", "&quot;") + "\"");
                        initialRecordCell = true;
                    }
                    salida.Append("]\n");
                    salida.Append("}");
                    initialRecord = true;
                }
                salida.Append("]\n");
                salida.Append("}");
                if (!endResponse)
                    return salida.ToString();
                else
                    HttpContext.Current.Response.Write(salida.ToString());

                dataTable.Dispose();
                adapter.Dispose();
                conexion.CloseConnection();
            }
            catch (Exception ex)
            {
                ErrorManagement.LogError(ex, HttpContext.Current, conexion);
                ErrorManagement.SendErrorLog();
                conexion.CloseConnection();
            }
            if (endResponse)
                HttpContext.Current.Response.End();
            return null;
        }

        public static string XMLGrid(string FieldList, string where, string sort, string limit, int dataPage, int dataPageSize, bool endResponse, bool sumarTotales)
        {
            dbConnector conexion = new dbConnector();
            OdbcDataAdapter adapterConteo = new OdbcDataAdapter(FieldList + where, conexion.connector);
            DataTable dataTableConteo = new DataTable();
            try
            {
                int registrosTotales = adapterConteo.Fill(dataTableConteo);
                OdbcDataAdapter adaptor = new OdbcDataAdapter(FieldList + where + sort + limit, conexion.connector);
                DataTable dataTable = new DataTable();
                adaptor.Fill(dataTable);

                HttpContext.Current.Response.AddHeader("Expires", " Mon, 26 Jul 1997 05:00:00 GMT");
                HttpContext.Current.Response.AddHeader("Last-Modified", DateTime.UtcNow.ToString());
                HttpContext.Current.Response.AddHeader("Cache-Control", " no-cache, must-revalidate");
                HttpContext.Current.Response.AddHeader("Pragma", "no-cache");
                HttpContext.Current.Response.AddHeader("Content-type", "text/xml;charset=utf-8");


                StringBuilder salida = new StringBuilder();
                StringBuilder registros = new StringBuilder();
                int paginasTotales = registrosTotales / dataPageSize;
                if ((registrosTotales % dataPageSize) > 0) paginasTotales++;
                salida.Append("<rows>\n");
                salida.Append("<page>" + dataPage + "</page>\n");
                salida.Append("<total>" + paginasTotales + "</total>\n");
                salida.Append("<records>" + registrosTotales + "</records>\n");
                double[] totales = new double[dataTableConteo.Columns.Count];
                string[] totalesLabel = new string[dataTableConteo.Columns.Count];
                bool isFirstRow = true;
                foreach (DataRow dataRow in dataTable.Rows)
                {
                    registros.Append("<row id=\"" + dataRow["id"] + "\">\n");
                    //if (dataRow.Table.Columns.Contains("rowStatus"))
                    //{
                    //    salida.Append("\"rowStatus\":\"" + dataRow["rowStatus"] + "\",");
                    //}
                    bool tipoCadena = false;
                    int indexItem = 0;
                    foreach (object item in dataRow.ItemArray)
                    {
                        if (item.GetType() == typeof(String))
                            tipoCadena = true;
                        registros.Append("<cell>");
                        if (tipoCadena)
                            registros.Append("<![CDATA[ ");
                        registros.Append(item.ToString());
                        if (tipoCadena)
                            registros.Append(" ]]>");
                        registros.Append("</cell>\n");
                        if (sumarTotales && IsNumeric(item) && indexItem > 0)
                        {
                            totales[indexItem] += Convert.ToDouble(item);
                        }
                        tipoCadena = false;
                        if (isFirstRow && indexItem > 0 && IsNumeric(item))
                            totalesLabel[indexItem] = dataTable.Columns[indexItem].ColumnName;
                        indexItem++;
                    }
                    registros.Append("</row>\n");
                    isFirstRow = false;

                }
                if (sumarTotales)
                {
                    int idxTotales = 0;
                    foreach (double tot in totales)
                    {

                        if (dataTable.Columns[idxTotales].DataType == typeof(Decimal) || dataTable.Columns[idxTotales].DataType == typeof(Int32) || dataTable.Columns[idxTotales].DataType == typeof(Int64) || dataTable.Columns[idxTotales].DataType == typeof(Double))
                            salida.Append(" <userdata name=\"" + totalesLabel[idxTotales] + "\">" + tot + "</userdata>");
                        idxTotales++;
                    }
                }
                salida.Append(registros);
                salida.Append("</rows>");
                if (!endResponse)
                    return salida.ToString();
                else
                    HttpContext.Current.Response.Write(salida.ToString());

                dataTableConteo.Dispose();
                adapterConteo.Dispose();
                conexion.CloseConnection();
            }
            catch (Exception ex)
            {
                ErrorManagement.LogError(ex, HttpContext.Current, conexion);
                ErrorManagement.SendErrorLog();
                conexion.CloseConnection();
            }
            if (endResponse)
                HttpContext.Current.Response.End();
            return null;
        }

        public static PaginacionXML GetPaginacionXML()
        {
            PaginacionXML datos = new PaginacionXML();

            int dataPage = Convert.ToInt32(HttpContext.Current.Request["page"]);
            int rowsPerPage = Convert.ToInt32(HttpContext.Current.Request["rows"]);
            string sortname = HttpContext.Current.Request["sidx"];
            string sortorder = HttpContext.Current.Request["sord"];
            if (sortname == null) sortname = "id";
            if (sortorder == null) sortorder = "desc";
            datos.SortOrder = " ORDER BY " + sortname + " " + sortorder + " ";
            if (dataPage == 0) dataPage = 1;
            if (rowsPerPage == 0) rowsPerPage = 30;
            int start = ((dataPage - 1) * rowsPerPage);
            datos.Limit = " LIMIT " + start + ", " + rowsPerPage + " ";
            datos.RowsPerPage = rowsPerPage;
            datos.DataPage = dataPage;
            return datos;
        }

        public static string ToXML(object objeto)
        {
            try
            {
                String XmlizedString = null;
                MemoryStream memoryStream = new MemoryStream();
                XmlSerializer xs = new XmlSerializer(objeto.GetType());
                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

                xs.Serialize(xmlTextWriter, objeto);
                memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
                XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
                return XmlizedString;
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e);
                return e.Message;
            }
        }

        //public static void ToXML(string nombreArchivo, string directorioSalida, object objeto)
        //{

        //    DirectoryInfo Direct = new DirectoryInfo(ConfigurationManager.AppSettings["sitePath"] + directorioSalida);
        //    if (!Direct.Exists)
        //        Direct.Create();
        //    string archivo = ConfigurationManager.AppSettings["sitePath"] + directorioSalida + nombreArchivo + ".xml";
        //    SaveStreamToFile(archivo, ToXML(objeto));


        //}


        public static void SaveStreamToFile(string fileFullPath, Stream stream)
        {
            if (stream.Length == 0) return;

            // Create a FileStream object to write a stream to a file
            FileStream fileStream = System.IO.File.Create(fileFullPath, (int)stream.Length);

            // Fill the bytes[] array with the stream data
            byte[] bytesInStream = new byte[stream.Length];
            stream.Read(bytesInStream, 0, (int)bytesInStream.Length);

            // Use FileStream object to write to the specified file
            fileStream.Write(bytesInStream, 0, bytesInStream.Length);
            fileStream.Close();

        }



    }

    public class SaltedHash
    {
        HashAlgorithm HashProvider;
        int SalthLength;
        protected string DomainSalt = "N8tWXA==";

        /// <summary>
        /// The constructor takes a HashAlgorithm as a parameter.
        /// </summary>
        /// <param name="HashAlgorithm">
        /// A <see cref="HashAlgorithm"/> HashAlgorihm which is derived from HashAlgorithm. C# provides
        /// the following classes: SHA1Managed,SHA256Managed, SHA384Managed, SHA512Managed and MD5CryptoServiceProvider
        /// </param>

        internal SaltedHash(HashAlgorithm HashAlgorithm, int theSaltLength)
        {
            HashProvider = HashAlgorithm;
            SalthLength = theSaltLength;
        }

        /// <summary>
        /// Default constructor which initialises the SaltedHash with the SHA256Managed algorithm
        /// and a Salt of 4 bytes ( or 4*8 = 32 bits)
        /// </summary>

        public SaltedHash()
            : this(new SHA256Managed(), 4)
        {
        }

        /// <summary>
        /// The actual hash calculation is shared by both GetHashAndSalt and the VerifyHash functions
        /// </summary>
        /// <param name="Data">A byte array of the Data to Hash</param>
        /// <param name="Salt">A byte array of the Salt to add to the Hash</param>
        /// <returns>A byte array with the calculated hash</returns>

        private byte[] ComputeHash(byte[] Data, byte[] Salt)
        {
            // Allocate memory to store both the Data and Salt together
            byte[] DataAndSalt = new byte[Data.Length + SalthLength];

            // Copy both the data and salt into the new array
            Array.Copy(Data, DataAndSalt, Data.Length);
            Array.Copy(Salt, 0, DataAndSalt, Data.Length, SalthLength);

            // Calculate the hash
            // Compute hash value of our plain text with appended salt.
            return HashProvider.ComputeHash(DataAndSalt);
        }

        public string GetStringHash(string originalString, string salt)
        {
            byte[] Data = Encoding.UTF8.GetBytes(originalString);
            byte[] Salt = Encoding.UTF8.GetBytes(salt);
            byte[] Hash;

            // Compute hash value of our data with the salt.
            Hash = ComputeHash(Data, Salt);
            return Convert.ToBase64String(Hash);
        }


        /// <summary>
        /// Given a data block this routine returns both a Hash and a Salt
        /// </summary>
        /// <param name="Data">
        /// A <see cref="System.Byte"/>byte array containing the data from which to derive the salt
        /// </param>
        /// <param name="Hash">
        /// A <see cref="System.Byte"/>byte array which will contain the hash calculated
        /// </param>
        /// <param name="Salt">
        /// A <see cref="System.Byte"/>byte array which will contain the salt generated
        /// </param>

        public void GetHashAndSalt(byte[] Data, out byte[] Hash, out byte[] Salt)
        {
            // Allocate memory for the salt
            Salt = new byte[SalthLength];

            // Strong runtime pseudo-random number generator, on Windows uses CryptAPI
            // on Unix /dev/urandom
            RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();

            // Create a random salt
            random.GetNonZeroBytes(Salt);

            // Compute hash value of our data with the salt.
            Hash = ComputeHash(Data, Salt);
        }

        /// <summary>
        /// The routine provides a wrapper around the GetHashAndSalt function providing conversion
        /// from the required byte arrays to strings. Both the Hash and Salt are returned as Base-64 encoded strings.
        /// </summary>
        /// <param name="Data">
        /// A <see cref="System.String"/> string containing the data to hash
        /// </param>
        /// <param name="Hash">
        /// A <see cref="System.String"/> base64 encoded string containing the generated hash
        /// </param>
        /// <param name="Salt">
        /// A <see cref="System.String"/> base64 encoded string containing the generated salt
        /// </param>

        public void GetHashAndSaltString(string Data, out string Hash, out string Salt)
        {
            byte[] HashOut;
            byte[] SaltOut;

            // Obtain the Hash and Salt for the given string
            GetHashAndSalt(Encoding.UTF8.GetBytes(Data), out HashOut, out SaltOut);

            // Transform the byte[] to Base-64 encoded strings
            Hash = Convert.ToBase64String(HashOut);
            Salt = Convert.ToBase64String(SaltOut);
        }

        /// <summary>
        /// This routine verifies whether the data generates the same hash as we had stored previously
        /// </summary>
        /// <param name="Data">The data to verify </param>
        /// <param name="Hash">The hash we had stored previously</param>
        /// <param name="Salt">The salt we had stored previously</param>
        /// <returns>True on a succesfull match</returns>

        public bool VerifyHash(byte[] Data, byte[] Hash, byte[] Salt)
        {
            byte[] NewHash = ComputeHash(Data, Salt);

            //  No easy array comparison in C# -- we do the legwork
            if (NewHash.Length != Hash.Length) return false;

            for (int Lp = 0; Lp < Hash.Length; Lp++)
                if (!Hash[Lp].Equals(NewHash[Lp]))
                    return false;

            return true;
        }

        /// <summary>
        /// This routine provides a wrapper around VerifyHash converting the strings containing the
        /// data, hash and salt into byte arrays before calling VerifyHash.
        /// </summary>
        /// <param name="Data">A UTF-8 encoded string containing the data to verify</param>
        /// <param name="Hash">A base-64 encoded string containing the previously stored hash</param>
        /// <param name="Salt">A base-64 encoded string containing the previously stored salt</param>
        /// <returns></returns>

        public bool VerifyHashString(string Data, string Hash, string Salt)
        {
            byte[] HashToVerify = Convert.FromBase64String(Hash);
            byte[] SaltToVerify = Convert.FromBase64String(Salt);
            byte[] DataToVerify = Encoding.UTF8.GetBytes(Data);
            return VerifyHash(DataToVerify, HashToVerify, SaltToVerify);
        }

        public bool VerifiDomainHash(string DomainName, string Hash)
        {
            return VerifyHashString(DomainName, Hash, DomainSalt);
        }

        public string CreateDomainHash(string DomainName)
        {

            byte[] Hash;
            byte[] SaltToVerify;
            if (CurrentUser.NivelUsuario == 9 && CurrentUser.Email == "webmaster.weblogsmexico.com")
                SaltToVerify = Convert.FromBase64String(DomainSalt);
            else
            {
                SaltToVerify = new byte[4];

                // Strong runtime pseudo-random number generator, on Windows uses CryptAPI
                // on Unix /dev/urandom
                RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();

                // Create a random salt
                random.GetNonZeroBytes(SaltToVerify);
            }
            byte[] DataToVerify = Encoding.UTF8.GetBytes(DomainName);
            Hash = ComputeHash(DataToVerify, SaltToVerify);
            return Convert.ToBase64String(Hash);
        }




    }

    public class ParametroTransformacionXML
    {
        private string _nombreParametro;
        private string _parametro;

        public string NombreParametro { get { return _nombreParametro; } set { _nombreParametro = value; } }
        public string Parametro { get { return _parametro; } set { _parametro = value; } }

        public ParametroTransformacionXML(string nombre, string contenido)
        {
            _nombreParametro = nombre;
            _parametro = contenido;
        }
    }
}
